package com.mlt.back.utils;

import java.sql.*;
import java.util.ResourceBundle;

/**
 * 数据库工具类，便于JDBC 代码编写
 */
public class DBUtil {

    private DBUtil(){}
    private  static ResourceBundle bundle=ResourceBundle.getBundle("db");
    private static String driver=bundle.getString("driver");
    private static String url=bundle.getString("url");
    private static String user=bundle.getString("user");
    private static String password=bundle.getString("password");
    private static ThreadLocal<Connection> local=new ThreadLocal<>();
    //注册驱动(类加载时自动加载静态代码块，只且执行一次)
    static{
        try {
            Class.forName(driver);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    public static Connection getConnection() throws SQLException {
        Connection conn=local.get();
        if (conn==null) {
            conn = DriverManager.getConnection(url, user, password);
            local.set(conn);
        }
        return conn;
    }

    /**
     * 关闭数据库所有资源
     * @param conn 连接对象
     * @param stmt  操作对象
     * @param rs    查询对象
     */
    public static void close(Connection conn, Statement stmt, ResultSet rs){
        if (rs!=null){
            try {
                rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (stmt!=null){
            try {
                stmt.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (conn!=null){
            try {
                conn.close();
                local.remove();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}
